package com.example.testapp;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.testapp.api.ApiClient;
import com.example.testapp.api.ApiService;
import com.example.testapp.model.BookData;
import com.example.testapp.model.ChangePasswordRequest;
import com.example.testapp.model.UserResponse;
import com.example.testapp.model.UserUpdateRequest;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class UserDetailActivity extends AppCompatActivity {
    private static final String TAG = "UserDetailActivity";
    private int userId;
    private EditText etUsername;
    private TextView tvAccount;
    private TextView tvRecordCount;
    private TextView tvRecordDays;
    private Button btnEdit;
    private Button btnLogout;
    private boolean isEditing = false;
    private UserResponse originalUser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_detail);

        Log.d(TAG, "进入用户详情页面");

        // 获取传递过来的用户ID
        userId = getIntent().getIntExtra("userId", 0);
        Log.d(TAG, "接收到的用户ID: " + userId);

        // 初始化UI组件
        initViews();

        // 设置返回按钮事件
        ImageView ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(v -> onBackPressed());

        // 设置退出按钮的点击事件
        btnLogout = findViewById(R.id.btn_logout);
        btnLogout.setOnClickListener(v -> {
            // 清除登录信息
            clearLoginInfo();
            // 跳转到登录页面
            Intent intent = new Intent(UserDetailActivity.this, LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            finish();
        });

        // 设置编辑按钮的点击事件
        btnEdit = findViewById(R.id.btn_edit);
        btnEdit.setOnClickListener(v -> {
            if (isEditing) {
                saveUserChanges();
            } else {
                enableEditMode(true);
            }
        });

        // 获取用户详情
        fetchUserDetail();

        // 获取记账记录数
        fetchRecordCount();
    }

    private void initViews() {
        etUsername = findViewById(R.id.tv_username);
        tvAccount = findViewById(R.id.tv_account);
        tvRecordCount = findViewById(R.id.tv_record_count);
        tvRecordDays = findViewById(R.id.tv_record_days);

        TextView tvChangePassword = findViewById(R.id.tv_change_password);
        tvChangePassword.setOnClickListener(v -> showChangePasswordDialog());
        // 新增：初始化注销账户文本并设置点击事件
        TextView tvDeleteAccount = findViewById(R.id.tv_delete_account);
        tvDeleteAccount.setOnClickListener(v -> showDeleteAccountDialog());

        // 添加用户名点击事件
        etUsername.setOnClickListener(v -> {
            if (!isEditing) {
                enableEditMode(true);
            }
        });
    }

    private void fetchUserDetail() {
        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        Call<UserResponse> call = apiService.getUserDetail(userId);

        call.enqueue(new Callback<UserResponse>() {
            @Override
            public void onResponse(Call<UserResponse> call, Response<UserResponse> response) {
                if (response.isSuccessful() && response.body() != null) {
                    originalUser = response.body();
                    Log.d(TAG, "获取用户详情成功: " + originalUser.getUsername());

                    // 计算记账天数
                    long daysBetween = calculateDaysBetween(originalUser.getAddTime());

                    // 更新UI
                    runOnUiThread(() -> {
                        etUsername.setText(originalUser.getUsername());
                        tvAccount.setText(originalUser.getAccount());
                        tvRecordDays.setText("您已经累计记账" + daysBetween + "天");

                        // 初始化为不可编辑状态
                        enableEditMode(false);
                    });
                } else {
                    Log.e(TAG, "获取用户详情失败: " + response.code());
                    showErrorDialog("获取用户信息失败");
                }
            }

            @Override
            public void onFailure(Call<UserResponse> call, Throwable t) {
                Log.e(TAG, "网络请求失败: " + t.getMessage());
                showErrorDialog("网络连接失败");
            }
        });
    }

    // 计算从注册到现在的时间差（天数）
    private long calculateDaysBetween(long addTimeMillis) {
        long currentTimeMillis = System.currentTimeMillis();
        long diff = currentTimeMillis - addTimeMillis;
        return TimeUnit.MILLISECONDS.toDays(diff);
    }

    private void fetchRecordCount() {
        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        Call<List<BookData>> call = apiService.getBookDataList(userId);

        call.enqueue(new Callback<List<BookData>>() {
            @Override
            public void onResponse(Call<List<BookData>> call, Response<List<BookData>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    int count = response.body().size();
                    Log.d(TAG, "获取记账记录数成功: " + count);

                    runOnUiThread(() ->
                            tvRecordCount.setText(String.valueOf(count))
                    );
                } else {
                    Log.e(TAG, "获取记账记录失败: " + response.code());
                    tvRecordCount.setText("0");
                    showErrorDialog("获取记账记录失败");
                }
            }

            @Override
            public void onFailure(Call<List<BookData>> call, Throwable t) {
                Log.e(TAG, "网络请求失败: " + t.getMessage());
                tvRecordCount.setText("0");
                showErrorDialog("网络连接失败");
            }
        });
    }

    private void enableEditMode(boolean enable) {
        isEditing = enable;

        // 设置编辑框状态
        etUsername.setEnabled(enable);
        etUsername.setFocusableInTouchMode(enable);
        etUsername.setFocusable(enable);

        if (enable) {
            etUsername.requestFocus();
            // 显示软键盘
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(etUsername, InputMethodManager.SHOW_IMPLICIT);
        } else {
            // 隐藏软键盘
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(etUsername.getWindowToken(), 0);
        }

        // 更改按钮文本和颜色
        btnEdit.setText(enable ? "保存" : "编辑");
        btnEdit.setTextColor(enable ?
                getResources().getColor(android.R.color.holo_green_dark) :
                getResources().getColor(android.R.color.black));

        btnLogout.setVisibility(enable ? View.GONE : View.VISIBLE);
    }

    private void saveUserChanges() {
        String newUsername = etUsername.getText().toString().trim();

        // 验证输入
        if (TextUtils.isEmpty(newUsername)) {
            Toast.makeText(this, "用户名不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        // 如果用户名没有修改，直接退出编辑模式
        if (newUsername.equals(originalUser.getUsername())) {
            enableEditMode(false);
            return;
        }

        // 构建更新请求（只设置用户名）
        UserUpdateRequest request = new UserUpdateRequest();
        request.setId(userId);
        request.setUsername(newUsername);

        // 发送更新请求
        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        Call<Void> call = apiService.updateUser(request);

        call.enqueue(new Callback<Void>() {
            @Override
            public void onResponse(Call<Void> call, Response<Void> response) {
                if (response.isSuccessful()) {
                    Log.d(TAG, "用户名更新成功");
                    Toast.makeText(UserDetailActivity.this, "用户名更新成功", Toast.LENGTH_SHORT).show();

                    // 更新原始用户数据
                    originalUser.setUsername(newUsername);

                    // 退出编辑模式
                    enableEditMode(false);
                } else {
                    Log.e(TAG, "用户名更新失败: " + response.code());
                    showErrorDialog("更新失败，请重试");
                }
            }

            @Override
            public void onFailure(Call<Void> call, Throwable t) {
                Log.e(TAG, "网络请求失败: " + t.getMessage());
                showErrorDialog("网络连接失败");
            }
        });
    }

    // 添加显示修改密码对话框的方法
    private void showChangePasswordDialog() {
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_change_password, null);
        EditText etOldPassword = dialogView.findViewById(R.id.et_old_password);
        EditText etNewPassword = dialogView.findViewById(R.id.et_new_password);
        EditText etConfirmPassword = dialogView.findViewById(R.id.et_confirm_password);

        MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
        builder.setTitle("修改密码")
                .setView(dialogView)
                .setPositiveButton("确定", (dialog, which) -> {
                    String oldPassword = etOldPassword.getText().toString().trim();
                    String newPassword = etNewPassword.getText().toString().trim();
                    String confirmPassword = etConfirmPassword.getText().toString().trim();

                    if (validatePasswords(oldPassword, newPassword, confirmPassword)) {
                        changePassword(userId, oldPassword, newPassword);
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    // 添加密码验证方法
    private boolean validatePasswords(String oldPassword, String newPassword, String confirmPassword) {
        if (TextUtils.isEmpty(oldPassword)) {
            Toast.makeText(this, "请输入当前密码", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (TextUtils.isEmpty(newPassword)) {
            Toast.makeText(this, "请输入新密码", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (newPassword.length() < 6) {
            Toast.makeText(this, "新密码长度至少为6位", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (!newPassword.equals(confirmPassword)) {
            Toast.makeText(this, "两次输入的新密码不一致", Toast.LENGTH_SHORT).show();
            return false;
        }

        return true;
    }

    // 添加修改密码的API调用方法
    private void changePassword(int userId, String oldPassword, String newPassword) {
        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        // 创建请求对象
        ChangePasswordRequest request = new ChangePasswordRequest(userId, oldPassword, newPassword);

        Call<Void> call = apiService.changePassword(request);
        call.enqueue(new Callback<Void>() {
            @Override
            public void onResponse(Call<Void> call, Response<Void> response) {
                if (response.isSuccessful()) {
                    Log.d(TAG, "密码修改成功");
                    Toast.makeText(UserDetailActivity.this, "密码修改成功，请重新登录", Toast.LENGTH_SHORT).show();

                    // 清除登录信息并跳转到登录页面
                    clearLoginInfo();
                    Intent intent = new Intent(UserDetailActivity.this, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    finish();
                } else {
                    try {
                        String errorBody = response.errorBody() != null ?
                                response.errorBody().string() : "无错误信息";
                        Log.e(TAG, "密码修改失败: " + response.code() + ", 错误信息: " + errorBody);
                        showErrorDialog("密码修改失败: " + errorBody);
                    } catch (IOException e) {
                        e.printStackTrace();
                        showErrorDialog("密码修改失败，请重试");
                    }
                }
            }

            @Override
            public void onFailure(Call<Void> call, Throwable t) {
                Log.e(TAG, "网络请求失败: " + t.getMessage());
                showErrorDialog("网络连接失败");
            }
        });
    }

    // 新增：显示注销账户确认对话框
    private void showDeleteAccountDialog() {
        new AlertDialog.Builder(this)
                .setTitle("注销账户")
                .setMessage("确定要注销账户吗？此操作不可恢复，所有数据将被删除。")
                .setNegativeButton("取消", null)
                .setPositiveButton("确定", (dialog, which) -> deleteAccount(userId))
                .show();
    }

    // 新增：调用注销账户API
    private void deleteAccount(int userId) {
        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        Call<Void> call = apiService.deleteUser(userId);  // 调用后端删除接口

        call.enqueue(new Callback<Void>() {
            @Override
            public void onResponse(Call<Void> call, Response<Void> response) {
                if (response.isSuccessful()) {
                    Log.d(TAG, "账户注销成功");
                    Toast.makeText(UserDetailActivity.this, "账户注销成功", Toast.LENGTH_SHORT).show();

                    // 清除登录信息并跳转到登录页面
                    clearLoginInfo();
                    Intent intent = new Intent(UserDetailActivity.this, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    finish();
                } else {
                    try {
                        String errorBody = response.errorBody() != null ?
                                response.errorBody().string() : "无错误信息";
                        Log.e(TAG, "账户注销失败: " + response.code() + ", 错误信息: " + errorBody);
                        showErrorDialog("账户注销失败: " + errorBody);
                    } catch (IOException e) {
                        e.printStackTrace();
                        showErrorDialog("账户注销失败，请重试");
                    }
                }
            }

            @Override
            public void onFailure(Call<Void> call, Throwable t) {
                Log.e(TAG, "网络请求失败: " + t.getMessage());
                showErrorDialog("网络连接失败");
            }
        });
    }

    private void showErrorDialog(String message) {
        new AlertDialog.Builder(this)
                .setTitle("错误")
                .setMessage(message)
                .setPositiveButton("确定", null)
                .show();
    }

    private void clearLoginInfo() {
        // 清除 SharedPreferences 中的登录信息
        getSharedPreferences("AppPrefs", MODE_PRIVATE).edit().clear().apply();
    }
}